<?php

namespace liketp;

class Config
{
    protected $config = [];

    public function __construct($configDir = '')
    {
        if (is_dir($configDir)) {
            $this->loadFiles($configDir);
        }
    }

    protected function loadFiles($dir)
    {
        $files = scandir($dir);

        foreach ($files as $file) {
            if (in_array($file, ['.', '..'])) continue;

            if (file_exists($dir . $file)) {

                if (is_dir($dir . $file)) {
                    // ignore dir.
                } else {
                    $key = pathinfo($dir . $file)['filename'];
                    $this->config[$key] = include($dir . $file);
                }
            }
        }
    }

    public function config($key = null, $default = null)
    {
        $argNum = func_num_args();

        if ($argNum == 0) {
            return $this->config;
        } else {
            if (is_array($key)) {
                foreach ($key as $k => $v) {
                    $this->set($k, $v);
                }
            } else {
                return $this->get($key, $default);
            }
        }
        return null;
    }

    public function get($key, $default = null, array $data = [])
    {
        $keyList = explode('.', $key);
        $data = empty($data) ? $this->config : $data;

        while (count($keyList)) {
            $k = array_shift($keyList);

            if (is_array($data) && isset($data[$k])) {
                $data = $data[$k];
            } else {
                return $default;
            }
        }

        return $data;
    }

    public function set($key, $val)
    {
        $keyList = explode('.', $key);
        $data = $this->config;
        $itemList = [$data];

        foreach ($keyList as $k) {
            if (is_array($data)) {
                $data = $data[$k] ?? [];
            } else {
                $data = [];
            }
            $itemList[] = $data;
        }

        $keyList = array_reverse($keyList);
        $itemList = array_reverse($itemList);
        array_shift($itemList);

        foreach ($keyList as $i => $k) {
            $item = $itemList[$i];
            $item[$k] = $val;
            $val = $item;
        }

        $this->config = $item;
    }
}
